#!/usr/bin/env python
#
#Copyright (c) 2009 NARI-TECH, All Rights Reserved.
#
#Created: Gong Chengming, 8 Dec., 2010
#

import getopt
import os
import string
import sys

def IsSection(base_name):
  id = string.find(base_name, '-')
  if -1 == id:
    return False, ""
  else:
    sec_name = base_name[id + 1 : ]
    idot = string.rfind(base_name, '.')
    if idot != -1:
      sec_name = base_name[id + 1 : idot]
    sec_name = sec_name.replace("&", "\\&")\
      .replace("#", "\\#")\
      .replace("%", "\\%")\
      .replace("$", "\\$")\
      .replace("_", "\\_")\
      .replace("{", "\\{")\
      .replace("}", "\\}")\
      .replace("^", "\\^{}")\
      .replace("~", "\\~{}")\
      .replace("@slash@", "/")\
      .replace("@backslash@", "$\\backslash$")
#    if -1 == idot:
#      return True, base_name[id + 1 : ]
#    else:
#      return True, base_name[id + 1 : idot]
    return True, sec_name


def merge(f, dir_name, level):
  if not os.path.isfile(dir_name) and not os.path.isdir(dir_name):
    print "Error: ", dir_name, " is not a file or directory."

  base_name = os.path.basename(dir_name)

  if '#' == base_name[0]:
    return


  suffix = ""
  idot = string.rfind(base_name, '.')
  if idot != -1:
    suffix = base_name[idot+1 : ]
#  print "suffix: ", suffix
  if "bak" == suffix or "orig" == suffix or "hidden" == suffix:
#    print "ignored!"
    return

  is_sec, sec_name = IsSection(base_name)

  sub_sec_tag = ["chapter", "section", "subsection", "subsubsection"][min(level, 3)]

  if is_sec:
    f.write("\n\\begin{")
    f.write(sub_sec_tag)
    f.write("}{")
    f.write(sec_name)
    f.write("}\n")
 
  if os.path.isfile(dir_name):
    nf = open(dir_name)
    f.write(nf.read())
    nf.close()
  else:
    files = os.listdir(dir_name)
    files.sort()
    for sub_dir in files:
      merge(f, os.path.join(dir_name, sub_dir), level + 1)
  
  if is_sec:
    f.write("\n\\end{")
    f.write(sub_sec_tag)
    f.write("}\n")

def main(argv):
  ofname = "preview"

  try:
    opts, args = getopt.getopt(argv, "o:", [])
  except getopt.GetoptError:
    print "Usage: latex_merge.py [-o outfilename]"
    sys.exit(2)

  for opt, arg in opts:
    if "-o" == opt:
      ofname = arg

  texf = open(os.path.join("tex/",ofname+".tex"), 'w')

  texf.write("\n\\input{../ctl/ctl.tex}\n")
  texf.write("\n\\begin{document}\n")

  merge(texf, "txt", -1)
  texf.write("\n\\end{document}\n")
  texf.close()

if __name__ == "__main__":
  main(sys.argv[1:])

